package com.cmy.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;


//
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");

        PrintWriter writer = resp.getWriter();
        //Cookie保存在客户端
        Cookie[] cookies = req.getCookies();//这里返回数组,可能存在多个

        //判断cookie是否存在
        if (cookies!=null){
            //如果存在
            writer.print("<h1>您上一次访问的时间为:</h1>");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的名字
                if (cookie.getName().equals("LastLoginTime")){
                    //获取cookie的值
                    long l = Long.parseLong(cookie.getValue());
                    Date date = new Date(l);
                    writer.write(date.toLocaleString());
                }

            }
        }else {
            writer.print("<h1>这是您第一次访问网站</h1>");
        }
        //服务器给客户端响应一个cookie
        Cookie cookie = new Cookie("LastLoginTime",System.currentTimeMillis()+"");
        cookie.setMaxAge(5);
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

    